package com.tripupdater.view
{
	import com.google.maps.Map;
	import com.google.maps.MapEvent;
	import com.google.maps.MapType;
	import com.google.maps.overlays.Marker;
	import com.google.maps.overlays.MarkerOptions;
	import com.google.maps.services.ClientGeocoder;
	import com.google.maps.services.GeocodingEvent;
	import com.google.maps.services.GeocodingResponse;
	import com.google.maps.services.Placemark;
	import com.tripupdater.event.TUEvent;
	import com.tripupdater.model.Model;
	import com.tripupdater.model.Params;
	
	import flash.display.MovieClip;
	import flash.geom.Point;

	[Event(name="mapLoaded", type="com.tripupdater.event.TUEvent")]
	public class MapView extends MovieClip
	{
		private var model:Model;
		private var map:Map;
		private var secretKey:String;
		private var placemark:Placemark;
		
		public function MapView()
		{
			super();
		
			model= Model.getInstance();
		}
		
		public function createMap():void
		{
			map= new Map();
			map.key= Params.GOOGLE_MAPS_KEY;
			map.addEventListener(MapEvent.MAP_READY, onMapReady);
			map.setSize(new Point(238, 147));
			map.visible= false;
			addChild(map);
		}
		
		private function onMapReady(e:MapEvent):void
		{
			dispatchEvent(new TUEvent(TUEvent.MAP_LOADED));
		}
		
		public function getPosition():void
		{
			trace("Searching position");
			var geoPos:ClientGeocoder= new ClientGeocoder();
			geoPos.addEventListener(GeocodingEvent.GEOCODING_SUCCESS, onGeoPos);
			geoPos.geocode(model.getCurrentPosition());
		}
		
		private function onGeoPos(e:GeocodingEvent):void
		{
			var resp:GeocodingResponse= e.response;
			placemark= resp.placemarks[0] as Placemark;
		
			setupMap();
		}
		
		private function setupMap():void
		{	
			var marker:Marker= new Marker(placemark.point);
			var markerOptions:MarkerOptions= new MarkerOptions();
			markerOptions.icon= new MyMarker();
			markerOptions.iconOffset= new Point(0, 20);
			marker.setOptions(markerOptions);
			
			map.enableScrollWheelZoom();
			map.enableDragging();
			map.enableContinuousZoom();
			map.enableControlByKeyboard();
			map.addOverlay(marker);
			map.setCenter(placemark.point, 12, MapType.NORMAL_MAP_TYPE);
			map.mouseChildren= false;
			map.useHandCursor= true;
			map.buttonMode= true;
			map.focusRect= false;
			map.visible= true;
		}
	}
}